package han.cirno.corrupt.components.school.impl

import okhttp3.Cookie
import okhttp3.CookieJar
import okhttp3.HttpUrl
import java.io.Serializable

class SerializableCookies: Serializable,CookieJar {
    private val markDelete=ArrayList<SerializableCookie>()
    val cookies = ArrayList<SerializableCookie>()
    companion object{
        const val MAX_DATE = 253402300799999L
    }

    override fun loadForRequest(url: HttpUrl): List<Cookie> {
        val outCookies = ArrayList<Cookie>()
        cookies.forEach {
            if (it.expiresAt <= System.currentTimeMillis()) {
                markDelete.add(it)
                return@forEach
            }
            if (
                (if (it.domain!=null) url.host.endsWith(it.domain) else false)
                && url.encodedPath.startsWith(it.path)) {
                outCookies.add(it.toCookie())
                return@forEach
            }
            return@forEach
        }
        markDelete.forEach { cookies.remove(it) }
        return outCookies
    }

    override fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>) {
        cookies.forEach {
            val c=this.cookies.find {c->
                c.domain==it.domain&&c.path==it.path&& c.name==it.name}
            if (c!=null) this.cookies.remove(c)
            this.cookies.add(SerializableCookie(it))
        }
    }

    data class SerializableCookie(
        val name : String?,
        val value : String?,
        val expiresAt : Long= MAX_DATE,
        val domain : String?,
        val path : String="/",
        val secure : Boolean=false,
        val httpOnly : Boolean=false,
        val persistent:Boolean=false,
        val hostOnly : Boolean=false
    ) : Serializable{
        constructor(cookie: Cookie) : this(
            cookie.name,
            cookie.value,
            cookie.expiresAt,
            cookie.domain,
            cookie.path,
            cookie.secure,
            cookie.httpOnly,
            cookie.persistent,
            cookie.hostOnly)

        fun toCookie(): Cookie {
            val builder = Cookie.Builder().path(path)
            name?.let { builder.name(it) }
            value?.let { builder.value(it) }
            domain?.let { builder.domain(it) }
            if (expiresAt!= MAX_DATE)builder.expiresAt(expiresAt)
            if (secure) builder.secure()
            if (hostOnly) builder.httpOnly()
            return builder.build()
        }
    }
}